home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / CXX / Bicycle.h < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.9 KB  |  84 lines

  1. //: CXX:Bicycle.h
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Complex class involving dynamic aggregation
  7. #ifndef BICYCLE_H
  8. #define BICYCLE_H
  9. #include <vector>
  10. #include <string>
  11. #include <iostream>
  12. #include <typeinfo>
  13.  
  14. class LeakChecker {
  15.   int count;
  16. public:
  17.   LeakChecker() : count(0) {}
  18.   void print() {
  19.     std::cout << count << std::endl; 
  20.   }
  21.   ~LeakChecker() { print(); }
  22.   void operator++(int) { count++; }
  23.   void operator--(int) { count--; }
  24. };
  25.  
  26. class BicyclePart {
  27.   static LeakChecker lc;
  28. public:
  29.   BicyclePart() { lc++; }
  30.   virtual BicyclePart* clone() = 0;
  31.   virtual ~BicyclePart() { lc--; }
  32.   friend std::ostream& 
  33.   operator<<(std::ostream& os, BicyclePart* bp) {
  34.     return os << typeid(*bp).name();
  35.   }
  36.   friend class Bicycle;
  37. };
  38.  
  39. enum BPart {
  40.   Frame, Wheel, Seat, HandleBar, 
  41.   Sprocket, Deraileur,
  42. };
  43.  
  44. template<BPart id> 
  45. class Part : public BicyclePart {
  46. public:
  47.   BicyclePart* clone() { return new Part<id>; }
  48. };
  49.  
  50. class Bicycle {
  51. public:
  52.   typedef std::vector<BicyclePart*> VBP;
  53.   Bicycle();
  54.   Bicycle(const Bicycle& old);
  55.   Bicycle& operator=(const Bicycle& old);
  56.   // [Other operators as needed go here:]
  57.   // [...]
  58.   // [...]
  59.   ~Bicycle() { purge(); }
  60.   // So you can change parts on a bike (but be 
  61.   // careful: you must clean up any objects you
  62.   // remove from the bicycle!)
  63.   VBP& bikeParts() { return parts; }
  64.   friend std::ostream& 
  65.   operator<<(std::ostream& os, Bicycle* b);
  66.   static void print(std::vector<Bicycle*>& vb, 
  67.     std::ostream& os = std::cout);
  68. private:
  69.   static int counter;
  70.   int id;
  71.   VBP parts;
  72.   void purge();
  73. };
  74.  
  75. // Both the Bicycle and the generator should 
  76. // provide more variety than this. But this gives
  77. // you the idea.
  78. struct BicycleGenerator {
  79.   Bicycle* operator()() {
  80.     return new Bicycle();
  81.   }
  82. }; 
  83. #endif // BICYCLE_H ///:~
  84.